import React, { Key, useEffect, useState } from "react";
import { useLocation, Location } from "react-router-dom";
import { Card, Col, message, Pagination, Row, Table, Tag, Tree } from "antd";
import {
  getDepartmentRequest,
  getScheduleRuleRequest,
  findSourceListRequest,
} from "@/api/hospital/hospitalList";
import type {
  getDepartmentReturnType,
  bookingScheduleListType,
  findSourceListReturnType,
} from "@/api/hospital/model/hospitalListTypes";

export default function HospitalSchedule() {
  function useMyLocation<T>() {
    type L = Location & { state: T };
    return useLocation() as L;
  }
  const { hoscode } = useMyLocation<{ hoscode: string }>().state;

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(5);
  const [depCode, setDepCode] = useState("");
  const [total, setTotal] = useState(0);
  const [workDate, setWorkDate] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [reRender, setReRender] = useState(false);
  const [departmentList, setDepartmentList] = useState<getDepartmentReturnType>(
    []
  );
  const [scheduleList, setScheduleList] = useState<bookingScheduleListType>([]);
  const [sourceList, setSourceList] = useState<findSourceListReturnType>([]);
  useEffect(() => {
    const getDepList = async () => {
      const re = await getDepartmentRequest(hoscode as string);
      // console.log(re);
      setDepartmentList(re);
      setDepCode((re[0].children as getDepartmentReturnType)[0].depcode);
    };
    getDepList();
  }, []);

  useEffect(() => {
    if (!depCode) return;
    const getTimeList = async () => {
      const re = await getScheduleRuleRequest(page, limit, hoscode, depCode);
      setScheduleList(re.bookingScheduleList);
      setWorkDate(re.bookingScheduleList[0]?.workDate);
      setTotal(re.total);
    };
    getTimeList();
  }, [depCode, page, limit, reRender]);

  useEffect(() => {
    if (!workDate) {
      return setSourceList([]);
    }
    setIsLoading(true);
    const getSource = async () => {
      const re = await findSourceListRequest(hoscode, depCode, workDate);
      setSourceList(re);
      setIsLoading(false);
    };
    getSource();
  }, [workDate]);

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费用（元）",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];

  const tapClickHandle = (workDate: string) => {
    return () => {
      setWorkDate(workDate);
    };
  };

  const pageChangeHandle = (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
  };

  const depChangeHandle = (depCodeArr: Key[]) => {
    setDepCode(depCodeArr[0] as string);
    message.error("没有数据");
  };

  return (
    <div>
      <Card>
        <Row gutter={20}>
          <Col span={5}>
            <Tree
              style={{
                height: 445,
                overflow: "auto",
                backgroundColor: "#f0f5ff",
                border: "1px solid #adc6ff",
              }}
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              onSelect={depChangeHandle}
              treeData={departmentList as []}
              fieldNames={{
                key: "depcode",
                title: "depname",
              }}
            />
          </Col>
          <Col span={18}>
            <div>
              {scheduleList.map((item) => {
                return (
                  <Tag
                    color="geekblue"
                    key={item.workDate}
                    onClick={tapClickHandle(item.workDate)}
                    style={{
                      backgroundColor:
                        workDate === item.workDate ? "skyblue" : "",
                    }}
                  >
                    <p>
                      {item.workDate}-{item.dayOfWeek}
                    </p>
                    <p>
                      {item.availableNumber}/{item.reservedNumber}
                    </p>
                  </Tag>
                );
              })}
              <Pagination
                style={{ margin: "20px 0" }}
                current={page}
                pageSize={limit}
                total={total}
                onChange={pageChangeHandle}
              />
              <Table
                loading={isLoading}
                columns={columns}
                dataSource={sourceList}
                pagination={false}
                bordered
                rowKey={"id"}
              />
            </div>
          </Col>
        </Row>
      </Card>
    </div>
  );
}
